package com.aceleeyy.apb.exception;

import com.aceleeyy.apb.base.ApbStatus;
import com.aceleeyy.apb.base.R;
import com.google.common.base.Throwables;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.HttpClientErrorException;

/**
 * API-统一异常处理
 *
 * @author Ace Lee
 * @version 1.0
 * @date 2020/8/10 10:41
 **/
@Slf4j
@ControllerAdvice
public class ApbExceptionHandler {

    /**
     * -------- 通用异常处理方法 --------
     **/
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R error(Exception e) {
        log.error(Throwables.getStackTraceAsString(e));
        return R.custom().fail();    // 通用异常结果
    }

    /**
     * --------空指针异常处理方法 --------
     **/
    @ExceptionHandler(NullPointerException.class)
    @ResponseBody
    public R error(NullPointerException e) {
        log.error(Throwables.getStackTraceAsString(e));
        return R.custom().fail(ApbStatus.NULL_POINTER_EXCEPTION);
    }

    /**
     * --------角标越界异常处理方法 --------
     **/
    @ExceptionHandler(HttpClientErrorException.class)
    @ResponseBody
    public R error(IndexOutOfBoundsException e) {
        log.error(Throwables.getStackTraceAsString(e));
        return R.custom().fail(ApbStatus.BUSINESS_HANDLE_EXCEPTION);
    }

    /**
     * -------- 自定义定异常处理方法 --------
     **/
    @ExceptionHandler(ApbException.class)
    @ResponseBody
    public R error(ApbException e) {
        log.error(Throwables.getStackTraceAsString(e));
        return R.custom().fail(e.getCode(),e.getMessage());
    }
}